<?php

namespace App\Http\Controllers;

use App\Constants\AppConstants;
use Illuminate\Http\Request;
use Inertia\Inertia;

class NotificationController extends Controller
{
    // 获取通知列表
    public function index(Request $request)
    {
        $query = auth()->user()->notifications();
        
        // 分类筛选
        if ($request->filled('category')) {
            $query->where('data->category', $request->category);
        }
        
        // 已读/未读筛选
        if ($request->filled('read')) {
            $read = filter_var($request->read, FILTER_VALIDATE_BOOLEAN);
            $query->{$read ? 'whereNotNull' : 'whereNull'}('read_at');
        }
        
        $notifications = $query->latest()->paginate(AppConstants::PAGINATION_NOTIFICATION_DEFAULT);
        
        return Inertia::render('Shop/Notifications/Index', [
            'notifications' => $notifications,
            'unreadCount' => auth()->user()->unreadNotifications()->count(),
            'filters' => $request->only(['category', 'read'])
        ]);
    }
    
    // 标记为已读
    public function markAsRead(Request $request)
    {
        $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'string|exists:notifications,id'
        ]);
        
        auth()->user()->notifications()
            ->whereIn('id', $request->ids)
            ->whereNull('read_at')
            ->update(['read_at' => now()]);
            
        return back()->with('success', '已标记为已读');
    }
    
    // 全部标记为已读
    public function markAllAsRead()
    {
        auth()->user()->unreadNotifications()->update(['read_at' => now()]);
        return back()->with('success', '全部已标记为已读');
    }
    
    // 删除通知（软删除）
    public function destroy(Request $request)
    {
        $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'string|exists:notifications,id'
        ]);
        
        auth()->user()->notifications()
            ->whereIn('id', $request->ids)
            ->delete();
            
        return back()->with('success', '删除成功');
    }
    
    // 获取未读数量（API）
    public function unreadCount()
    {
        return response()->json([
            'count' => auth()->user()->unreadNotifications()->count()
        ]);
    }
    
    // 获取最近通知（API）
    public function recent()
    {
        $notifications = auth()->user()->notifications()
            ->latest()
            ->limit(5)
            ->get();
            
        return response()->json([
            'notifications' => $notifications
        ]);
    }
}
